const express = require('express');
const router = express.Router();
const pool = require('./db');

// 添加选择题
router.post('/api/add-choice-question', async (req, res) => {
    // 增强请求体验证
    if (!req.body || typeof req.body !== 'object') {
        return res.status(400).json({ 
            success: false,
            message: '无效的请求体格式'
        });
    }

    const {
        practice_id,
        question_order,
        question,
        option_a,
        option_b,
        option_c,
        option_d,
        correct_answer,
        score
    } = req.body;

    //console.log('请求体内容:', JSON.stringify(req.body, null, 2));

    // 增强字段验证
    if (practice_id === undefined || question_order === undefined || question === undefined || 
        option_a === undefined || option_b === undefined || correct_answer === undefined || 
        score === undefined) {
        return res.status(400).json({ 
            success: false,
            message: '缺少必填字段',
            missingFields: {
                practice_id: practice_id === undefined,
                question_order: question_order === undefined,
                question: question === undefined,
                option_a: option_a === undefined,
                option_b: option_b === undefined,
                correct_answer: correct_answer === undefined,
                score: score === undefined
            }
        });
    }

    try {
        await pool.execute(
            'INSERT INTO choice_questions (practice_id, question_order, question, option_a, option_b, option_c, option_d, correct_answer, score) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [practice_id, question_order, question, option_a, option_b, option_c, option_d, correct_answer, score]
        );
        res.json({ success: true, message: '选择题添加成功' });
    } catch (error) {
        console.error('Error adding choice question:', error);
        res.status(500).json({ 
            success: false, 
            message: '添加选择题失败',
            error: error.message 
        });
    }
});

// 添加填空题
router.post('/api/add-fill-question', async (req, res) => {
    const { practice_id, question_order, question, blanks } = req.body;

    // 验证必填字段
    if (!practice_id || isNaN(question_order) || !question || !blanks) {
        return res.status(400).json({ 
            success: false,
            message: '缺少必填字段'
        });
    }

    try {
        await pool.execute(
            'INSERT INTO fill_questions (practice_id, question_order, question, blank1_answer, blank1_score, blank2_answer, blank2_score, blank3_answer, blank3_score) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [
                practice_id,
                question_order,
                question,
                blanks[0]?.answer || null,
                blanks[0]?.score || null,
                blanks[1]?.answer || null,
                blanks[1]?.score || null,
                blanks[2]?.answer || null,
                blanks[2]?.score || null
            ]
        );
        res.json({ success: true, message: '填空题添加成功' });
    } catch (error) {
        console.error('Error adding fill question:', error);
        res.status(500).json({ 
            success: false, 
            message: '添加填空题失败',
            error: error.message 
        });
    }
});

// 添加解答题
router.post('/api/add-essay-question', async (req, res) => {
    const { practice_id, question_order, question, score } = req.body;

    // 验证必填字段
    if (!practice_id || isNaN(question_order) || !question || isNaN(score)) {
        return res.status(400).json({ 
            success: false,
            message: '缺少必填字段'
        });
    }

    try {
        await pool.execute(
            'INSERT INTO essay_questions (practice_id, question_order, question, score) VALUES (?, ?, ?, ?)',
            [practice_id, question_order, question, score]
        );
        res.json({ success: true, message: '解答题添加成功' });
    } catch (error) {
        console.error('Error adding essay question:', error);
        res.status(500).json({ 
            success: false, 
            message: '添加解答题失败',
            error: error.message 
        });
    }
});

router.post('/clear-remaining-submit-times', async (req, res) => {
    try {
        const { userId, practiceId } = req.body;
        const [rows] = await pool.execute('UPDATE commited_practice SET remaining_submit_times = 0 WHERE commit_user_id = ? AND practice_id = ?', [userId, practiceId]);
        if (rows.affectedRows > 0) {
            res.json({ success: true, message: '剩余提交次数已清零' });
        } else {
            res.json({ success: false, message: '清零失败，未找到对应的记录' });
        }
    } catch (error) {
        console.error('清零剩余提交次数出错:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

module.exports = router;
